/**
* ...
* @author Default
* @version 0.1
*/

package org.anivision.plugins {
	import de.polygonal.ds.HashTable;
	import flash.events.*;
	import org.anivision.eval.Eval;

	public class PluginInfo extends EventDispatcher {
		
		private var _pluginNode		:XML;
		private var _config			:XML;
		private var _eval			:Eval;
		private var _path			:String;
		private var _scripts:Array;
		private var _loadedScripts	:int		= 0;
		
		public function PluginInfo(pluginNode:XML, eval:Eval, path) {
			_pluginNode = pluginNode;
			_path = path;
			_eval = eval;
			_scripts = new Array();
		}
		
		public function __onLoad(e:Event):void {
			_config = new XML(e.target.data);
			
			for each(var load:XML in _config.child('load'))
			{
				var scriptsName:String = load.toString();
				if ( scriptsName.length > 0 )
				{
					// split string into file list
					var files:Array = scriptsName.split(';');
					var instance:String;
					if ( load.attribute('instance').length == 1 )
						instance = load.@instance;
					
					// append path to file names
					var paths:Array = new Array();
					for each(var f:String in files)
					{
						paths.push(_path + '/' + f);
					}
					
					// create script loader to take care of merging the script list into one swf
					var script:ScriptLoader = new ScriptLoader(paths, instance);					
					
					script.addEventListener(Event.COMPLETE,			__onScriptComplete);
					script.addEventListener(IOErrorEvent.IO_ERROR,	__onScriptLoadError);
					_scripts.push(script);
					
					script.load();
				}
			}			
		}
		
		private function __onScriptLoadError(e:Event):void {
			trace(this._pluginNode.@name + '...ERROR.');
			var error:IOErrorEvent = new IOErrorEvent(IOErrorEvent.IO_ERROR);
			this.dispatchEvent(error);
		}
		private function __onScriptComplete(e:Event):void {
			trace(this._pluginNode.@name + '...DONE.');
			this._loadedScripts++;
			
			var progress:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS);
			progress.bytesTotal		= 100;
			progress.bytesLoaded	= (this._loadedScripts * 100) / this._scripts.length;
			
			this.dispatchEvent(progress);

			if ( this._loadedScripts == this._scripts.length )
			{
				loadScripts();
			}
		}
		
		private function loadScripts()
		{
			for each(var script:ScriptLoader in _scripts)
			{
				if ( script.code != null )
					_eval.eval(script.code);
			}
			
			this.dispatchEvent(new Event(Event.COMPLETE));
		}
	}
	
}
